package com.wyzz.hr.base;

import java.io.*;
import java.util.List;
import java.util.UUID;

import com.wyzz.hr.bo.IDepartmentBO;
import com.wyzz.hr.bo.IInmatchBO;
import com.wyzz.hr.bo.IIodefBo;
import com.wyzz.hr.bo.IOutmatchBO;
import com.wyzz.hr.bo.IOutmatchModelBO;
import com.wyzz.hr.io.extend.ExportInmatchModelToExcel;
import com.wyzz.hr.io.extend.ExportToExcel;
import com.wyzz.hr.pojo.InmatchModel;
import com.wyzz.hr.pojo.Iodef;
import com.wyzz.hr.pojo.OutmatchModel;
import com.wyzz.hr.spring.SpringBeanFactory;
import com.wyzz.hr.util.impl.PropertiesFileConfigManager;
import com.wyzz.hr.util.output.FieldOperate;
import com.wyzz.hr.util.output.ObjectListToListList;

public class BaseDownloadAction extends BaseAction {

	public BaseDownloadAction() {
		docStream = null;
		contentDisposition = null;
		serverFileName = null;
	}

	private Iodef getIodefByName(String ioName) {
		IIodefBo iodefBO = (IIodefBo) SpringBeanFactory.getBean("iodefbo");
		Iodef iodef = iodefBO.loadObjectByName(ioName);
		return iodef;
	}

	public boolean download(String fileNameWithPath, String showName) {
		try {
			File file = new File(fileNameWithPath);
			FileInputStream fileInputStream = new FileInputStream(file);
			setDocStream(fileInputStream);
			String downFileName = new String(showName.getBytes("gbk"),
					"ISO8859_1");
			System.out.println(downFileName);
			 setContentDisposition((new StringBuilder("attachment;")).append(
					"filename=\"").append(downFileName).append("\"").toString());
			setServerFileName(fileNameWithPath);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	public boolean excelDownload(List dbList, String ioName, String ommId,
			List fieldAddList) {
		if (dbList == null || dbList.size() < 1) {
			System.out.print("==========error : dbList==null");
			return false;
		}
		Iodef iodef = getIodefByName(ioName);
		if (iodef == null) {
			System.out.print("==========error : iodef==null");
			return false;
		}
		IOutmatchBO outmatchBO = (IOutmatchBO) SpringBeanFactory
				.getBean("outmatchBO");
		IOutmatchModelBO outmatchModelBO = (IOutmatchModelBO) SpringBeanFactory
				.getBean("outmatchModelBO");
		OutmatchModel outmatchModel;
		if (ommId == null || ommId.length() < 1)
			outmatchModel = outmatchModelBO.loadDefaultObject(iodef);
		else
			outmatchModel = outmatchModelBO.getObject(iodef, ommId);
		if (outmatchModel == null) {
			System.out.print("==========error : outmatchModel==null");
			return false;
		}
		outmatchModel.setOmmIo(iodef);
		System.out.println(outmatchModel.getOmmDesc());
		List fieldList = outmatchBO.getOutputList(outmatchModel);
		if (fieldAddList != null) {
			boolean addList = true;
			int i = 0;
			do {
				if (i >= fieldList.size())
					break;
				if (((FieldOperate) fieldList.get(i)).getFieldName().indexOf(
						"outPutList.") == 0) {
					addList = false;
					break;
				}
				i++;
			} while (true);
			if (addList)
				fieldList.addAll(fieldAddList);
		}
		if (fieldList.size() < 1) {
			System.out.print("==========error : fieldList.size()==0");
			return false;
		}
		try {
			ObjectListToListList ltsa = new ObjectListToListList(dbList,
					fieldList);
			ltsa.transferGroupOrderStatistic();
			String strArr[][] = ltsa.getListListToString();
			List statList = ltsa.getStatisticListToString();
			List groupPlace = ltsa.getGroupPlaceList();
			String xslFileName = (new StringBuilder()).append("export_")
					.append(UUID.randomUUID().toString()).append(
							PropertiesFileConfigManager.getInstance()
									.getProperty("sys.saveDir.type").trim())
					.toString();
			String filePath = (new StringBuilder()).append(
					FileOperate.getFileHomePath()).append(xslFileName)
					.toString();
			ExportToExcel exportToExcel = new ExportToExcel(filePath, strArr,
					fieldList, statList, groupPlace, outmatchModel);
			exportToExcel.exportOnce();
			return download(filePath, (new StringBuilder()).append(
					outmatchModel.getOmmName()).append(".xls").toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public String downloadToExcel(List dbList, String ioName, String ommId) {
		return downloadToExcel(dbList, ioName, ommId, null, null);
	}

	public String downloadToExcel(List dbList, String ioName, String ommId,
			String alias) {
		return downloadToExcel(dbList, ioName, ommId, alias, null);
	}

	public String downloadToExcel(List dbList, String ioName, String ommId,
			String alias, List fieldAddList) {
		IDepartmentBO deptBo = (IDepartmentBO) SpringBeanFactory
				.getBean("departmentBO");
		if (alias != null)
			if ("".equals(alias))
				deptBo.setListDeptLevels(dbList, "empDeptNo", "empBranch",
						"empDeptNo", new String[0]);
			else if ("transfer".equals(alias)) {
				deptBo.setListDeptLevels(dbList, "eftOldDeptNo",
						"eftOldBranch", "eftOldDeptNo",
						new String[] { "eftTransferDate" });
				deptBo.setListDeptLevels(dbList, "eftNewDeptNo",
						"eftNewBranch", "eftNewDeptNo", new String[0]);
			} else if ("empsalarypay".equals(alias))
				deptBo.setListDeptLevels(dbList, "espDept", "espBranch",
						"espDeptNo", new String[] { "espYearmonth" });
			else
				deptBo
						.setListDeptLevels(dbList, (new StringBuilder())
								.append(alias).append(".empDeptNo").toString(),
								(new StringBuilder()).append(alias).append(
										".empBranch").toString(),
								(new StringBuilder()).append(alias).append(
										".empDeptNo").toString(), new String[0]);
		if (dbList == null || dbList.size() == 0) {
			addActionError("\u6CA1\u6709\u6570\u636E\u53EF\u4EE5\u5BFC\u51FA\uFF01");// 没有数据可以导出
			// ！
			return "success";
		}
		Iodef iodef = getIodefByName(ioName);
		if (iodef == null) {
			addActionError("\u5BFC\u51FA\u63A5\u53E3\u4E0D\u5B58\u5728\uFF0C\u8BF7\u68C0\u67E5\u201C\u7CFB\u7EDF->\u6570\u636E\u63A5\u53E3\u914D\u7F6E\u201D\uFF01");
			// 导出接口不存在，请检查“系统->数据接口配置”！
			return "success";
		}
		if (excelDownload(dbList, ioName, ommId, fieldAddList)) {
			clearErrorsAndMessages();
			return "download";
		} else {
			addActionError("\u6570\u636E\u5BFC\u51FA\u5931\u8D25\uFF01");// 数据导出失败
			// ！
			return "success";
		}
	}

	public boolean excelModelDownload(InmatchModel inmatchModel) {
		BaseDownloadAction _tmp = this;
		IInmatchBO inmatchBO = (IInmatchBO) getBean("inmatchBO");
		List imList = inmatchBO.getInputList(inmatchModel);
		inmatchModel.setImList(imList);
		String filePath = FileOperate.getFileHomePath();
		String xslFileName = (new StringBuilder()).append("export_").append(
				UUID.randomUUID().toString()).append(
				PropertiesFileConfigManager.getInstance().getProperty(
						"sys.saveDir.type").trim()).toString();
		filePath = (new StringBuilder()).append(filePath).append(xslFileName)
				.toString();
		try {
			ExportInmatchModelToExcel exportInmatchModelToExcel = new ExportInmatchModelToExcel(
					filePath, inmatchModel);
			exportInmatchModelToExcel.exportOnce();
			return download(filePath, (new StringBuilder()).append(
					inmatchModel.getImmName()).append(".xls").toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public FileInputStream getDocStream() {
		return docStream;
	}

	public void setDocStream(FileInputStream docStream) {
		this.docStream = docStream;
	}

	public String getContentDisposition() {
		return contentDisposition;
	}

	public void setContentDisposition(String contentDisposition) {
		this.contentDisposition = contentDisposition;
	}

	public String getServerFileName() {
		return serverFileName;
	}

	public void setServerFileName(String serverFileName) {
		this.serverFileName = serverFileName;
	}

	private static final long serialVersionUID = 0x7627b229L;
	private FileInputStream docStream;
	private String contentDisposition;
	private String serverFileName;
}
